package com.lsu.iterator.homework;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

/**
 * 绘制直线的类
 *
 * @Author wang suo
 * @Date 2020/11/27 0027 14:17
 * @Version 1.0
 */
public class LineDrawer extends Frame {
    /**
     * List<Point>由多个点的列表组成线条，那么List<List<Point>> 有线条的列表组成的线条列表
     * 存放所有的线条
     */
    private List<List<Point>> lines = new ArrayList<>();
    /**
     * 当前线条
     */
    private List<Point> currLine;

    private LineDrawer(String title) {
        super(title);
        //adapter适配器
        //MouseAdapter接收鼠标事件的抽象适配器类
        addMouseListener(new MouseAdapter() {
            //当用户按下鼠标时就开始绘制一条新的线条
            @Override
            public void mousePressed(MouseEvent event) {
                //ArrayList<Point>把许多点放到一个数组列表里，成为一条直线
                currLine = new ArrayList<>();
                lines.add(currLine);
                currLine.add(new Point(event.getX(), event.getY()));
            }
        });

        //MouseMotionListener鼠标移动事件
        addMouseMotionListener(new MouseMotionAdapter() {
            //拖动鼠标，随之画线条
            @Override
            public void mouseDragged(MouseEvent event) {
                currLine.add(new Point(event.getX(), event.getY()));
                repaint();
            }
        });

        setSize(300, 300);
        setVisible(true);
    }

    @Override
    public void update(Graphics g) {
        paint(g);
    }

    @Override
    public void paint(Graphics g) {
        /*
         * Iterator<List<Point>>对List<Point>集合进行迭代。Iterator<E>迭代器，是java.util中的接口。
         * iterator()为接口java.util.List中的方法时,是返回以正确顺序在列表的元素上进行迭代的迭代器。
         */
        for (List<Point> line : lines) {
            Iterator<Point> points = line.iterator();
            int x1 = -1, y1 = -1, x2, y2;
            while (points.hasNext()) {
                Point point = points.next();
                x2 = (int) point.getX();
                y2 = (int) point.getY();
                if (x1 != -1) {
                    g.drawLine(x1, y1, x2, y2);
                }
                x1 = x2;
                y1 = y2;
            }
        }
    }

    public static void main(String[] args) {
        new LineDrawer("直线绘图");
    }
}
